package com.example.mallone11.merchant.merchant;

import com.example.mallone11.merchant.params.MerchantRequestParams;
import com.example.mallone11.merchant.pojo.Merchant;
import com.example.mallone11.merchant.service.MerchantService;
import com.example.mallone11.utils.MD5;
import com.example.mallone11.utils.R;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("merchant")
public class MerchantHandler {

    @Resource
    private MerchantService merchantService;

    @RequestMapping("add")
    public R addMerchant(@RequestBody MerchantRequestParams merchant) {
//        先调用查看数据库中是否存在即将要注册的账号
        Merchant merchant_obj = merchantService.findMerchantByName(merchant.getMname());
        if (merchant_obj != null) {
            return R.fail("您注册的用户名已存在");
        }
        merchant.setMpassword(MD5.getMD5Hash(merchant.getMpassword()));
        return merchantService.addMerchant(merchant) > 0 ? R.ok("注册成功") : R.fail("注册失败");
    }


    @RequestMapping("login")
    public R login(@RequestBody MerchantRequestParams merchant, HttpServletRequest request){
        merchant.setMpassword(MD5.getMD5Hash(merchant.getMpassword()));
        Merchant merchant_obj=merchantService.login(merchant);
        request.getSession().setAttribute("mname",merchant_obj);
        return merchant_obj != null ? R.ok("登陆成功"): R.fail("账号或密码错误");
    }

    @RequestMapping("update")
    public R updateMerchant(@RequestBody Merchant merchant,HttpServletRequest request){
        merchant.setMstatus(0);
        merchant.setMname(request.getSession().getAttribute("mname").toString());
        merchant.setUpdate_by(request.getSession().getAttribute("mname").toString());
        return merchantService.updateMerchant(merchant)> 0 ? R.ok("资料提交成功，请等待审核"): R.fail("资料提交失败，请重试");
    }
}












